<template>
  <el-form
    ref="ruleFormRef"
    :model="account"
    class="form"
    size="large"
    :rules="rules"
  >
    <el-form-item label="账号:" prop="name">
      <el-input v-model="account.name" />
    </el-form-item>

    <el-form-item label="密码:" prop="password">
      <el-input v-model="account.password" show-password />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { localCache } from "@/utils";
import { useStore } from "vuex";

const account = reactive({
  name: localCache.getCache("name") ?? "",
  password: localCache.getCache("password") ?? "",
});

let rules: FormRules = reactive({
  name: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [
    {
      required: true,
      pattern: /^[a-z0-9]{6,10}$/,
      trigger: "blur",
      message: "请输入6~10位的数字或小写字母面膜",
    },
  ],
});

const validatetForm = async (
  formEl: FormInstance | undefined
): Promise<boolean> => {
  if (!formEl) return false;
  let result = false;
  await formEl?.validate((valid) => valid && (result = valid));

  return result;
};

const ruleFormRef = ref<FormInstance>();

const store = useStore();

const submit = async (isKeep: boolean) => {
  let result = await validatetForm(ruleFormRef.value);

  if (!result) return result;
  if (isKeep) {
    localCache.setCache("name", account.name);
    localCache.setCache("password", account.password);
  } else {
    localCache.removeCache("name");
    localCache.removeCache("password");
  }

  store.dispatch("login/accountLoginAction", account);
};

defineExpose({
  submit,
});
</script>

<style lang="scss" scoped></style>
